package com.bmsbosmpa.controller;

import com.alibaba.fastjson.JSON;
import com.bmsbosmpa.controller.util.Message;
import com.bmsbosmpa.entity.Book;
import com.bmsbosmpa.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("books")
public class BookController {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public Message queryAll(int page) {
        return new Message(0, "Welcome!", JSON.toJSON(bookService.list()));
    }

    @DeleteMapping("{id}")
    public Message deleteBluk(@PathVariable List<Integer> id) {
        Message message = new Message();
        boolean ret = bookService.removeByIds(id);
        if (ret) {
            message.setMessage("删除成功");
            message.setStatus(0);
        } else {
            message.setMessage("删除失败");
            message.setStatus(1);
        }
        return message;
    }

    @PutMapping
    public Message update(@RequestBody Book book) {
        Message message = new Message();
        boolean ret = bookService.updateById(book);
        if (ret) {
            message.setMessage("编辑成功");
            message.setStatus(0);
        } else {
            message.setMessage("编辑失败");
            message.setStatus(1);
        }
        return message;
    }

    @PostMapping
    public Message save(@RequestBody Book book) {
        Message message = new Message();
        boolean ret = bookService.save(book);
        if (book == null) {
            message.setStatus(1);
            message.setMessage("");
        }else if (ret) {
            message.setMessage("添加成功");
            message.setStatus(0);
        } else {
            message.setMessage("添加失败");
            message.setStatus(1);
        }
        return message;
    }

}
